<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2020/8/10 0010
 * Time: 21:50
 */

/** 用法
 *  提交参数 username password email
 *  POST Methods:reg | isExist
 */
require_once "mysqlinfo.php";
require_once "phpass-0.5/PasswordHash.php";

$param_username = $_GET['username'];
$param_pwd = $_GET['password'];
$param_email = $_GET['email'];

$param_method = $_GET['method'];

$con = mysqli_connect(MYSQL_HOST,MYSQL_USERNAME,MYSQL_PASSWORD,MYSQL_DATABASE);
if (!$con) exit(json_encode(array("code" => CODE_CONNECT_FAILED)));

if ($param_method == "reg") {
    $hasher = new PasswordHash(8,false);
    $HashedPwd = $hasher->HashPassword($param_pwd);
    $sql = "SELECT * FROM `".TABLE_USER."` WHERE userName = '$param_username'";
    $resultSet = mysqli_query($con,$sql);
    if (mysqli_num_rows($resultSet) > 0) {
        exit(json_encode(array("code" => CODE_REGISTER_USERNAME_EXIST)));
    }
    $dataTime = date("Y-m-d H:i:s");
    $sql = "INSERT INTO `user` (`Id`, `cookie_id`, `userName`, `userPass`, `userEmail`, `userHeadImg`, `userSynopsis`, `registerTime`) VALUES (NULL, 0, '$param_username', '$HashedPwd', '$param_email', '', '', '$dataTime')";
    $result = mysqli_query($con,$sql);
    if ($result) {
        exit(json_encode(array("code" => CODE_REGISTER_SUCCESS)));
    }else {
        exit(json_encode(array("code" => CODE_REGISTER_FAILED)));
    }
}else if ($param_method == "isExist") {
    $sql = "SELECT * FROM `".TABLE_USER."` WHERE userName = '$param_username'";
    $resultSet = mysqli_query($con,$sql);
    if (mysqli_num_rows($resultSet) > 0) {
        exit(json_encode(array("code" => CODE_REGISTER_USERNAME_EXIST)));
    }
}else {
    exit(json_encode(array("code" => CODE_UNKNOWN_METHOD)));
}